// 通过拦截 response ,将yapi中没有接口填入 yapi
// 使用:
// 1.跨域浏览器
// 2.将下面代码填入 request.js 中
// import { yapi } from "../../yapi/autoFillMissingInterfaces.js";
// yapi.init()
// service.interceptors.response.use(res => {
// yapi.check(res)
//  ...

// http://127.0.0.1:3000/project/84/interface/api/cat_705
import axios from 'axios'
const baseURL = 'http://127.0.0.1:3000'
const token = 'eb604be9b2df56824a09d8aac17740ba0a1f98baf242ea5c1624d5e0ad4ceeec'
const project_id = 84
const catid = 705
const ajax = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: baseURL,

  // 超时
  timeout: 10000,
  headers: {
    'Access-Control-Allow-Origin': '*',
  },
})
export const yapi = {
  list: [],
  init() {
    return ajax
      .get('/api/interface/list', { params: { token } })
      .then((res) => {
        const list = res.data.data.list.map((item) => {
          return item.path
        })
        yapi.list = list
      })
  },
  add(res) {
    const tpl = {
      project_id: project_id,
      catid: catid,
      token: token,
      req_query: [],
      req_headers: [
        {
          name: 'Content-Type',
        },
      ],
      req_body_form: [],
      title: res.config.url,
      path: res.config.url,
      status: 'undone',
      res_body_type: 'json',
      res_body: JSON.stringify(res.data),
      switch_notice: false,
      message: '',
      desc: '<p><br></p>',
      method: res.config.method,
      req_params: [],
    }

    ajax({
      url: '/api/interface/add',
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      data: tpl,
    }).then((res) => {
      console.log('新增接口', res)
    })
  },
  check(res) {
    if (yapi.list.includes(res.config.url)) {
      return true
    }

    yapi.add(res)
  },
}
